import { Button, DataGrid, Popup, SelectBox, TextBox } from "devextreme-react";
import { useModel } from "umi";
import { DevToolBar, CpasIcon, DevGrid, LayoutB } from '~/public/cpas-ui';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import Toolbar, { Item } from 'devextreme-react/toolbar';
import { intl } from "@/utils";
import { CFLKMConfigUpdate, getCFLKMConfigDataList } from "../service"
import { Popover } from "antd";
import CarryEntryPopup from "~/public/cpas-business/components-bs/CarryEntryPopup";


const SetReclassiFiedItem: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { width, height, DataId } = props

    const diaParams = useRef<any>();
    const devGridRef = useRef<any>();
    const carryEntryRef = useRef<any>();
    const Data_ID = useRef<any>();

    const [visible, setVisible] = useState<boolean>(false);
    const [size, setSize] = useState<any>({ width, height });
    const [data, SetData] = useState<any[]>([])
    const [jfkmbh, setJFKMBH] = useState<string>('')
    const [dfkmbh, setDFKMBH] = useState<string>('')
    const [guid, setGUID] = useState<string>('')
    const [aa, setAdjustData] = useState<any[]>([])

    useImperativeHandle(ref, () => ({
        show: async (params: any) => {
            diaParams.current = params;
            setVisible(true);
            const r = await getCFLKMConfigDataList({
                dbname,
                Data_ID: DataId
            })
            SetData(r);
            Data_ID.current = DataId
        },
    }))

    // 点击关闭按钮逻辑
    const onHiding = () => {
        setVisible(false)
    }

    const columns = [
        {
            dataField: "JFKMMC",
            dataType: "string",
            caption: "借方科目",
            // width: 130,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
            cellRender: (cell: any) => {
                return <div style={{ display: 'flex', justifyContent: ' space-between' }}>
                    <div>
                        {cell.data.JFKMMC}
                    </div>
                    <div>
                        <CpasIcon type='icon-ellipsis' onClick={() => {
                            carryEntryRef.current.show({
                                dbname,
                                Data_ID: Data_ID.current,
                                // 是否显示总账
                                isHasFZZ: true,
                                editUser: username,
                                selectMode: "0",
                                // 选择 模式 0：单选 1：多选连机选择
                                auxiliaryState: true,
                                // 是否为辅助帐
                                okCallback: async (r: any) => {
                                    console.log(cell.rowIndex, 'cell.rowIndex-----');
                                    console.log(r.row.data.name, 'r.row.data.name-----');
                                    devGridRef.current.instance.cellValue(cell.rowIndex, 'JFKMMC', r.row.data.name);
                                    // const v = JSON.parse(JSON.stringify(r.row.data.KMBH))
                                    // setAdjustData((arr: any) => {
                                    //     const ars = [...arr];
                                    //     ars.push(v);
                                    //     return ars;
                                    // })
                                    setJFKMBH(r.row.data.KMBH)
                                },
                            })
                        }} />
                    </div>
                </div>
            }
        },
        {
            dataField: "DFKMMC",
            dataType: "string",
            caption: "贷方科目",
            // width: 130,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
            cellRender: (cell: any) => {
                return <div style={{ display: 'flex', justifyContent: ' space-between' }}>
                    <div>
                        {cell.data.DFKMMC}
                    </div>
                    <div>
                        <CpasIcon type='icon-ellipsis' onClick={() => {
                            carryEntryRef.current.show({
                                dbname,
                                Data_ID: Data_ID.current,
                                // 是否显示总账
                                isHasFZZ: true,
                                editUser: username,
                                selectMode: "0",
                                // 选择 模式 0：单选 1：多选连机选择
                                auxiliaryState: true,
                                // 是否为辅助帐
                                okCallback: async (r: any) => {
                                    devGridRef.current.instance.cellValue(cell.rowIndex, 'DFKMMC', r.row.data.name);
                                    setDFKMBH(r.row.data.KMBH)
                                },
                            })
                        }} />
                    </div>
                </div>
            }
        },
    ]
    const contents = (e: any) => {
        return <>{e}</>
    }
    // 添加
    const AddItem = useCallback(() => {
        return <div style={{ marginTop: '3px', marginRight: '8px', marginLeft: '8px' }}>
            <span>
                <Popover content={contents("增加")} placement="top">
                    <span>
                        <CpasIcon type='icon-add-circle' fontSize={18}
                            onClick={() => {
                                devGridRef.current.instance.addRow();
                            }}
                        />
                    </span>
                </Popover>
            </span>
        </div>
    }, [])

    // 删除
    const DeleteItem = useCallback(() => {
        return <div style={{ marginTop: '3px', marginRight: '15px' }}>
            <span>
                <Popover content={contents("删除")} placement="top">
                    <CpasIcon type='icon-minus-circle' fontSize={18}
                        onClick={() => {

                        }}
                    />
                </Popover>
            </span>
        </div>
    }, [])
    // const TopCellClick = (cell: any) => {
    //     setGUID(cell.key);
    //     setJFKMBH(cell.data.JFKMBH)
    //     setDFKMBH(cell.data.DFKMBH)
    // }
    const OK = async () => {
        const res = await CFLKMConfigUpdate({
            dbname,
            Data_ID: Data_ID.current,
            GUID: guid,
            JFKMBH: jfkmbh,
            DFKMBH: dfkmbh
        })
        setVisible(false)
        console.log(res, '----');
    }
    return (
        <div style={{ width: '100%', height: '100%' }}>
            <Popup
                width='100%'
                height="100%"
                shading={false}
                ref={ref}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
                visible={visible}
                title='设置自动重分类科目'
                minWidth={500}
                minHeight={300}
                {...props}
                {...size}
                onHiding={onHiding}
                onResizeEnd={(e) => {
                    setSize({ width: e.width, height: e.height });
                }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => setVisible(false)
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => OK()
                        },
                    },
                ]}
            >
                <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
                    <div style={{ width: '100%', height: '12%' }}>
                        <span>借方科目出现负值或贷方金额,重分类为贷方科目;贷方科目出现负值或者借方金额,重分类为借方科目;</span>
                    </div>
                    <div style={{ width: '100%', height: '80%' }}>
                        <Toolbar>
                            <Item location="before" render={AddItem} />
                            <Item location="before" render={DeleteItem} />
                            <Item location="before" text='默认为6大往来科目' />
                        </Toolbar>
                        <DevGrid.RangeTap
                            ref={devGridRef}
                            id="GUID"
                            dataSource={data}
                            keyExpr="GUID"
                            columnAutoWidth={true}
                            defaultColumns={columns}
                            showBorders={true}
                            showRowLines={true}
                            showColumnLines={true}
                            editing={{
                                allowAdding: false,
                                allowUpdating: false,
                                allowDeleting: false,
                                mode: "cell"
                            }}
                            paging={{
                                enabled: false
                            }}
                        // onCellClick={TopCellClick}
                        />
                    </div>
                </div >
            </Popup >
            <CarryEntryPopup ref={carryEntryRef} />
        </div >
    )
});

export default React.memo(SetReclassiFiedItem);
